package cn.fresh.xuanyuan.module.infra.api.column;

import cn.fresh.xuanyuan.framework.common.pojo.CommonResult;
import cn.fresh.xuanyuan.module.infra.dal.dataobject.column.MallColumnProductDO;
import cn.fresh.xuanyuan.module.infra.service.column.MallColumnProductService;
import cn.fresh.xuanyuan.module.product.api.spu.dto.ProductSpuRespDTO;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
@Slf4j
public class ColumnProductApiImpl implements ColumnProductApi {

    @Resource
    private MallColumnProductService mallColumnProductService;

    @Override
    public CommonResult<String> updateColumnProductInfo(ProductSpuRespDTO productSpuResp) {
        log.info("66666666666545454");
        if(productSpuResp != null && productSpuResp.getId() != null) {
            List<MallColumnProductDO> list = mallColumnProductService.getListBySpuId(productSpuResp.getId());
            if(CollectionUtil.isNotEmpty(list)) {
                for(MallColumnProductDO spu : list) {

                    int marketPrice = Optional.of(productSpuResp.getMarketPrice()).orElse(0);
                    if(marketPrice > 0) {
                        BigDecimal salePrice = new BigDecimal(marketPrice).divide(new BigDecimal(100), RoundingMode.HALF_UP);
                        spu.setSalePrice(salePrice);
                    }
                    int price = Optional.of(productSpuResp.getPrice()).orElse(0);
                    if(price > 0) {
                        BigDecimal payPrice = new BigDecimal(price).divide(new BigDecimal(100), RoundingMode.HALF_UP);
                        spu.setPayPrice(payPrice);
                    }

                    spu.setProductName(productSpuResp.getName());
                    spu.setProductImage(productSpuResp.getPicUrl());
                    spu.setUpdateTime(LocalDateTime.now());
                }
                mallColumnProductService.updateBatch(list);
            }
        }
        return CommonResult.success("success");
    }
}
